﻿using BlazorApp.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Model.Dtos;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Utils;
using WebApp.Comm;
using WebApp.Service;

namespace WebApp.Controllers
{

    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AccountController : ControllerBase
    {
        private readonly ILogger<AccountController> _logger;
        private readonly IOptionsMonitor<JwtOption> _jwtOpt;
        protected IUserService UserService { get; set; }

        public AccountController(ILogger<AccountController> logger, IOptionsMonitor<JwtOption> jwtOpt, IUserService dataService)
        {
            _logger = logger;
            _jwtOpt = jwtOpt;
            UserService = dataService;
        }

        [HttpPost]
        public async Task<IActionResult> Login([FromForm] LoginRqtDto rqtDto)
        {
            User user = UserService.Query(rqtDto.Account);//这里应该用redis
            if (user == null)
            {
                return Unauthorized();
            }

            //密码加盐
            var cryptedPwd = EncryptHelper.Encrypt(rqtDto.Password, EncryptHelper.ALGORITHM_SHA256, user.Salt);
            if (cryptedPwd != user.Password)
            {
                return Unauthorized();
            }
            var claims = new Claim[]
            {
                 new(ClaimTypes.NameIdentifier, user.Id.ToString()),
                 new(ClaimTypes.Name, rqtDto.Account),
                 new(ClaimTypes.Role, "admin")//TODO角色
            };
            var jwtSetting = _jwtOpt.CurrentValue;
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.UtcNow.AddHours(jwtSetting.ExpiryInHours);//用UtcNow
            var token = new JwtSecurityToken(jwtSetting.Issuer, jwtSetting.Audience, claims, expires: expiry, signingCredentials: creds);
            var tokenText = new JwtSecurityTokenHandler().WriteToken(token);
            return Ok(tokenText);
        }
    }
}
